#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()


import logging, os, base64, time, requests, json
from Crypto.Cipher import AES
from vouchers.certificate.AlipayClientConfig import AlipayClientConfig
from vouchers.certificate.CertDefaultAlipayClient import CertDefaultAlipayClient
from vouchers.certificate.AlipayUserDtbankActivitybillQueryRequest import AlipayUserDtbankActivitybillQueryModel, AlipayUserDtbankActivitybillQueryRequest
from alipay.aop.api.request.AlipaySystemOauthTokenRequest import AlipaySystemOauthTokenRequest
from alipay.aop.api.request.AlipayMarketingVoucherSendRequest import AlipayMarketingVoucherSendModel, AlipayMarketingVoucherSendRequest
from alipay.aop.api.request.AlipayMarketingVoucherQueryRequest import AlipayMarketingVoucherQueryModel, AlipayMarketingVoucherQueryRequest
from alipay.aop.api.request.AlipayUserDtbankcustChannelvoucherSendRequest import AlipayUserDtbankcustChannelvoucherSendModel, AlipayUserDtbankcustChannelvoucherSendRequest
from alipay.aop.api.request.AlipayFundTransUniTransferRequest import AlipayFundTransUniTransferModel, AlipayFundTransUniTransferRequest
from alipay.aop.api.request.AlipayFundTransCommonQueryRequest import AlipayFundTransCommonQueryModel, AlipayFundTransCommonQueryRequest
from alipay.aop.api.constant.CommonConstants import PYTHON_VERSION_3
from alipay.aop.api.request.AlipayTradeCreateRequest import AlipayTradeCreateModel, AlipayTradeCreateRequest
from alipay.aop.api.request.AlipayTradeQueryRequest import AlipayTradeQueryModel, AlipayTradeQueryRequest
from alipay.aop.api.request.AlipayUserDtbankcustActivityconfigQueryRequest import AlipayUserDtbankcustActivityconfigQueryModel, AlipayUserDtbankcustActivityconfigQueryRequest
from alipay.aop.api.request.AlipayUserDtbankcustActivityorderQueryRequest import AlipayUserDtbankcustActivityorderQueryModel, AlipayUserDtbankcustActivityorderQueryRequest
from alipay.aop.api.request.AlipayMarketingCampaignDrawcampTriggerRequest import AlipayMarketingCampaignDrawcampTriggerModel, AlipayMarketingCampaignDrawcampTriggerRequest
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5
from Crypto.Hash import SHA256, MD5
from Crypto.PublicKey import RSA

from vouchers.utils import voucherclient, client_jiangxi88, client_jiangxi88_jizhangben
from vouchers.utils import client as fun_client
from equity_mall.utils.utils import random_str, get_sign

BLOCK_SIZE = AES.block_size
pad = lambda s, length: s + (BLOCK_SIZE - length % BLOCK_SIZE) * chr(BLOCK_SIZE - length % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


def client():
    '''实例化阿里云对象'''
    # logging.basicConfig(
    #     level=logging.INFO,
    #     format='%(asctime)s %(levelname)s %(message)s',
    #     filemode='a', )
    # logger = logging.getLogger('')

    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = '2021003131606807'
    alipay_client_config.app_cert_sn = '121ab70f7b0ca91de95f47243bcd5c52'
    alipay_client_config.alipay_root_cert_sn = '687b59193f3f462dd5336e5abf83c5d8_02941eef3187dddf3d3b83462e1dfcf6'
    alipay_client_config.app_private_key = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'certificate/app_private_key.pem'), 'r').read()
    alipay_client_config.alipay_public_key = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'certificate/alipay_public_key.pem'), 'r').read()
    client = CertDefaultAlipayClient(alipay_client_config)
    return client


def new_client():
    '''实例化阿里云对象'''
    # logging.basicConfig(
    #     level=logging.INFO,
    #     format='%(asctime)s %(levelname)s %(message)s',
    #     filemode='a', )
    # logger = logging.getLogger('')

    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = '2021003141674282'
    # alipay_client_config.app_cert_sn = '354355316408997d18f382d9324c3334'
    # alipay_client_config.alipay_root_cert_sn = '687b59193f3f462dd5336e5abf83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VSbSqaVEqCFwxgtRcZLrjQoECgYEAiirXJz9GcQg2yIB9lpSlnm63rSZMYrkQUyLeJs1qQREkKNpKBDbPRJiOx89V+/odsnLXjuae+4Gopt8334jojeRHGTf4zB4iw1zhxyi7l5knriE9CiYfi3VlM093JkUZXH0D7nOmAP5zK4qP0tWlaAHl4P51J57OxHlxjY8Z7IECgYBKOHJEYOQbYe5U+bDMiichRH9Fb5Dnr7GElTz27xYWJMWcExihLYZZyGXgRhDf786UV4r/5nHOUSqm6UynXg8dK8L2ZcV9noqDdoetDaexHmzKD9DosTFFTpurvFEDkhhO+j7Ne8AqcUgr/0inpngIKWmtPLr2Q+n7m3KmlCgmAQKBgH47DVXcUtHtDgvr6Z2KdCh8O/IK06oLAgJ/7M3bwFJHpquTnEXEhHGs34toW0FHZEyIs+Yol1j+g1E3sTTCMno0BXw/qTnkuR+MtBTmrSxOXoERhwPp1weGd9TKY1KKExdRk8ztVJDj8c5gRQfbBX1TfymgbXHenVk3tPyBCamK'
    alipay_client_config.alipay_public_key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnUuLiiE8KugcnteQkWmceATljjNjAdusj+YKDtd/RfghtvRTTPOkXyafQAbg/WkmaWAUvpDSLcr1t+WPJAttz2PEDGBDnCrSCca5CPS2eS3umGl+f4P2xiMvdUsf7Z7plmbcQfyq1PrHRywsSL77Gc10UiX+hUWcTTwKlF6oPQZqCZ8Y2AJ0o0hPEC2UGtThrPt78vMFvjTBDQm4Lkx0eNRzfaNRLrQ5h+e+sUKlsD+LZgMh+xZBmyF6NMujfZ+jJiGlU4FAHSovCupGNZsKrxr5Criv3kQqw+VR7fr4LC6rTYxk9RmFSu+/L2R6lCPWgWC6LXeJ5Ab03KSyaStJywIDAQAB'
    client = CertDefaultAlipayClient(alipay_client_config)
    return client


client = client()
new_client = new_client()


class AlipayOpen():

    def __init__(self):

        self.client = client
        self.new_client = new_client
        self.voucherclient = voucherclient
        self.fun_client = fun_client
        self.client_jiangxi88 = client_jiangxi88
        self.client_jiangxi88_jizhangben = client_jiangxi88_jizhangben

    def systemoauthtoken(self, code):
        request = AlipaySystemOauthTokenRequest()
        request.grant_type = 'authorization_code'
        request.code = code
        response_content = self.client.execute(request)
        return response_content

    def new_systemoauthtoken(self, code):
        request = AlipaySystemOauthTokenRequest()
        request.grant_type = 'authorization_code'
        request.code = code
        response_content = self.new_client.execute(request)
        return response_content

    def getPhoneNumber(self, resContent):
        key = 'YhfaC3mBScAuEWDeOhwBRA=='  # 需要更换成自己的AES密钥
        charset = 'utf-8'
        iv = '\0' * BLOCK_SIZE
        encrypted_content = base64.b64decode(resContent)
        cryptor = AES.new(base64.b64decode(key), AES.MODE_CBC, iv.encode())
        content = unpad(cryptor.decrypt(encrypted_content))
        if PYTHON_VERSION_3:
            content = content.decode(charset)
        return content

    def new_getPhoneNumber(self, resContent):
        key = 'FmdjPngukP6IoHWu0ZaZgQ=='  # 需要更换成自己的AES密钥
        charset = 'utf-8'
        iv = '\0' * BLOCK_SIZE
        encrypted_content = base64.b64decode(resContent)
        cryptor = AES.new(base64.b64decode(key), AES.MODE_CBC, iv.encode())
        content = unpad(cryptor.decrypt(encrypted_content))
        if PYTHON_VERSION_3:
            content = content.decode(charset)
        return content

    def tradecreate(self, out_trade_no, total_amount, buyer_id, description):
        model = AlipayTradeCreateModel()
        model.out_trade_no = out_trade_no
        model.total_amount = float(total_amount)
        model.subject = description
        model.buyer_id = buyer_id
        request = AlipayTradeCreateRequest(biz_model=model)
        request.notify_url = 'https://api.sutpay.com/cpay/ali_result/'
        response_content = self.client.execute(request)
        return response_content

    def tradequery(self, out_trade_no):
        model = AlipayTradeQueryModel()
        model.out_trade_no = out_trade_no
        model.query_options = ['voucher_detail_list', 'trade_settle_info', 'fund_bill_list']
        request = AlipayTradeQueryRequest(biz_model=model)
        response_content = self.client.execute(request)
        return response_content

    def vouchersend(self, user_id, activity_id, out_biz_no):
        model = AlipayUserDtbankcustChannelvoucherSendModel()
        model.activity_id = activity_id
        model.user_id = user_id
        model.out_biz_no = out_biz_no
        request = AlipayUserDtbankcustChannelvoucherSendRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def vouchersend_login_id(self, user_id, activity_id, out_biz_no):
        model = AlipayUserDtbankcustChannelvoucherSendModel()
        model.activity_id = activity_id
        model.logon_id = user_id
        model.out_biz_no = out_biz_no
        request = AlipayUserDtbankcustChannelvoucherSendRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def campaign_drawcamp_trigger_login_id(self, user_id, activity_id, out_biz_no):
        '''营销抽奖活动触发抽奖'''
        model = AlipayMarketingCampaignDrawcampTriggerModel()
        model.camp_id = activity_id
        model.login_id = user_id
        model.out_biz_no = out_biz_no
        request = AlipayMarketingCampaignDrawcampTriggerRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def campaign_drawcamp_trigger_user_id(self, user_id, activity_id, out_biz_no):
        '''营销抽奖活动触发抽奖'''
        model = AlipayMarketingCampaignDrawcampTriggerModel()
        model.camp_id = activity_id
        model.user_id = user_id
        model.out_biz_no = out_biz_no
        request = AlipayMarketingCampaignDrawcampTriggerRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def voucherquery(self, voucher_id):
        model = AlipayMarketingVoucherQueryModel()
        model.voucher_id = voucher_id
        request = AlipayMarketingVoucherQueryRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def voucherbillquery(self, activity_id):
        model = AlipayUserDtbankActivitybillQueryModel()
        model.activity_id = activity_id
        model.bill_type = 'ALL'
        request = AlipayUserDtbankActivitybillQueryRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def transunitransfer_login_id(self, identity, name, out_biz_no, trans_amount, order_title):
        model = AlipayFundTransUniTransferModel()
        model.alipay_user_id = '2088631976752358'
        model.account_type = 'ACCTRANS_ACCOUNT'
        model.out_biz_no = out_biz_no
        model.trans_amount = str(trans_amount)
        model.product_code = 'TRANS_ACCOUNT_NO_PWD'
        model.biz_scene = 'DIRECT_TRANSFER'
        model.app_cert_sn = 'DIRECT_TRANSFER'
        payeeInfo = {
            "identity_type": "ALIPAY_LOGON_ID",
            "identity": identity,
            "name": name
        }
        model.payee_info = payeeInfo
        model.order_title = order_title
        model.remark = order_title
        model.business_params = {
            "payer_show_name_use_alias": True
        }
        request = AlipayFundTransUniTransferRequest(biz_model=model)
        response_content = self.fun_client.execute(request)
        if "SYSTEM_ERROR" in response_content:
            response_content = self.transunitransfer_query(out_biz_no)
            result = json.loads(response_content)
            if result['code'] == '10000':
                result['trans_date'] = result['pay_date']
            return json.dumps(result)
        return response_content

    def transunitransfer_user_id(self, identity, out_biz_no, trans_amount, order_title):
        model = AlipayFundTransUniTransferModel()
        model.alipay_user_id = '2088631976752358'
        model.account_type = 'ACCTRANS_ACCOUNT'
        model.out_biz_no = out_biz_no
        model.trans_amount = str(trans_amount)
        model.product_code = 'TRANS_ACCOUNT_NO_PWD'
        model.biz_scene = 'DIRECT_TRANSFER'
        model.app_cert_sn = 'DIRECT_TRANSFER'
        payeeInfo = {
            "identity_type": "ALIPAY_USER_ID",
            "identity": identity
        }
        model.payee_info = payeeInfo
        model.order_title = order_title
        model.remark = order_title
        model.business_params = {
            "payer_show_name_use_alias": True
        }
        request = AlipayFundTransUniTransferRequest(biz_model=model)
        response_content = self.fun_client.execute(request)
        if "SYSTEM_ERROR" in response_content:
            response_content = self.transunitransfer_query(out_biz_no)
            result = json.loads(response_content)
            if result['code'] == '10000':
                result['trans_date'] = result['pay_date']
            return json.dumps(result)
        return response_content

    def transunitransfer_query(self, out_biz_no):
        model = AlipayFundTransCommonQueryModel()
        model.product_code = 'TRANS_ACCOUNT_NO_PWD'
        model.biz_scene = 'DIRECT_TRANSFER'
        model.out_biz_no = out_biz_no
        request = AlipayFundTransCommonQueryRequest(biz_model=model)
        response_content = self.fun_client.execute(request)
        return response_content

    def transunitransfer_login_id_jiangxi88(self, identity, name, out_biz_no, trans_amount, order_title):
        model = AlipayFundTransUniTransferModel()
        model.alipay_user_id = '2088741038963832'
        model.account_type = 'ACCTRANS_ACCOUNT'
        model.out_biz_no = out_biz_no
        model.trans_amount = str(trans_amount)
        model.product_code = 'TRANS_ACCOUNT_NO_PWD'
        model.biz_scene = 'DIRECT_TRANSFER'
        model.app_cert_sn = 'DIRECT_TRANSFER'
        payeeInfo = {
            "identity_type": "ALIPAY_LOGON_ID",
            "identity": identity,
            "name": name
        }
        model.payee_info = payeeInfo
        model.order_title = order_title
        model.remark = order_title
        model.business_params = {
            "payer_show_name_use_alias": True
        }
        request = AlipayFundTransUniTransferRequest(biz_model=model)
        response_content = self.client_jiangxi88.execute(request)
        if "SYSTEM_ERROR" in response_content:
            response_content = self.transunitransfer_query_jiangxi88(out_biz_no)
            result = json.loads(response_content)
            if result['code'] == '10000':
                result['trans_date'] = result['pay_date']
            return json.dumps(result)
        return response_content

    def transunitransfer_user_id_jiangxi88(self, identity, out_biz_no, trans_amount, order_title):
        model = AlipayFundTransUniTransferModel()
        model.alipay_user_id = '2088741038963832'
        model.account_type = 'ACCTRANS_ACCOUNT'
        model.out_biz_no = out_biz_no
        model.trans_amount = str(trans_amount)
        model.product_code = 'TRANS_ACCOUNT_NO_PWD'
        model.biz_scene = 'DIRECT_TRANSFER'
        model.app_cert_sn = 'DIRECT_TRANSFER'
        payeeInfo = {
            "identity_type": "ALIPAY_USER_ID",
            "identity": identity
        }
        model.payee_info = payeeInfo
        model.order_title = order_title
        model.remark = order_title
        model.business_params = {
            "payer_show_name_use_alias": True
        }
        request = AlipayFundTransUniTransferRequest(biz_model=model)
        response_content = self.client_jiangxi88.execute(request)
        if "SYSTEM_ERROR" in response_content:
            response_content = self.transunitransfer_query_jiangxi88(out_biz_no)
            result = json.loads(response_content)
            if result['code'] == '10000':
                result['trans_date'] = result['pay_date']
            return json.dumps(result)
        return response_content

    def transunitransfer_query_jiangxi88(self, out_biz_no):
        model = AlipayFundTransCommonQueryModel()
        model.product_code = 'TRANS_ACCOUNT_NO_PWD'
        model.biz_scene = 'DIRECT_TRANSFER'
        model.out_biz_no = out_biz_no
        request = AlipayFundTransCommonQueryRequest(biz_model=model)
        response_content = self.client_jiangxi88.execute(request)
        return response_content

    def transunitransfer_login_id_jiangxi88_jizhangben(self, identity, name, out_biz_no, trans_amount, order_title):
        model = AlipayFundTransUniTransferModel()
        model.out_biz_no = out_biz_no
        model.trans_amount = str(trans_amount)
        model.product_code = 'SINGLE_TRANSFER_NO_PWD'
        model.biz_scene = 'ENTRUST_TRANSFER'
        model.payer_info = {
            "identity_type": "ACCOUNT_BOOK_ID",
            "identity": "2088940794176870",
            "ext_info": '{"agreement_no": "20245407172227749883"}'
        }
        payeeInfo = {
            "identity_type": "ALIPAY_LOGON_ID",
            "identity": identity,
            "name": name
        }
        model.payee_info = payeeInfo
        model.order_title = order_title
        model.remark = order_title
        model.business_params = {
            "payer_show_name_use_alias": True
        }
        request = AlipayFundTransUniTransferRequest(biz_model=model)
        response_content = self.client_jiangxi88_jizhangben.execute(request)
        if "SYSTEM_ERROR" in response_content:
            response_content = self.transunitransfer_query_jiangxi88_jizhangben(out_biz_no)
            result = json.loads(response_content)
            if result['code'] == '10000':
                result['trans_date'] = result['pay_date']
            return json.dumps(result)
        return response_content

    def transunitransfer_user_id_jiangxi88_jizhangben(self, identity, out_biz_no, trans_amount, order_title):
        model = AlipayFundTransUniTransferModel()
        model.out_biz_no = out_biz_no
        model.trans_amount = str(trans_amount)
        model.product_code = 'SINGLE_TRANSFER_NO_PWD'
        model.biz_scene = 'ENTRUST_TRANSFER'
        model.payer_info = {
            "identity_type": "ACCOUNT_BOOK_ID",
            "identity": "2088940794176870",
            "ext_info": '{"agreement_no": "20245407172227749883"}'
        }
        payeeInfo = {
            "identity_type": "ALIPAY_USER_ID",
            "identity": identity
        }
        model.payee_info = payeeInfo
        model.order_title = order_title
        model.remark = order_title
        model.business_params = {
            "payer_show_name_use_alias": True
        }
        request = AlipayFundTransUniTransferRequest(biz_model=model)
        response_content = self.client_jiangxi88_jizhangben.execute(request)
        if "SYSTEM_ERROR" in response_content:
            response_content = self.transunitransfer_query_jiangxi88_jizhangben(out_biz_no)
            result = json.loads(response_content)
            if result['code'] == '10000':
                result['trans_date'] = result['pay_date']
            return json.dumps(result)
        return response_content

    def transunitransfer_query_jiangxi88_jizhangben(self, out_biz_no):
        model = AlipayFundTransCommonQueryModel()
        model.product_code = 'SINGLE_TRANSFER_NO_PWD'
        model.biz_scene = 'ENTRUST_TRANSFER'
        model.out_biz_no = out_biz_no
        request = AlipayFundTransCommonQueryRequest(biz_model=model)
        response_content = self.client_jiangxi88_jizhangben.execute(request)
        return response_content

    def activityconfig_query(self, activity_id):
        model = AlipayUserDtbankcustActivityconfigQueryModel()
        model.activity_type = 'VOUCHER'
        model.activity_id = activity_id
        request = AlipayUserDtbankcustActivityconfigQueryRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content

    def activityorder_query(self, activity_id, out_biz_no, logon_id):
        model = AlipayUserDtbankcustActivityorderQueryModel()
        model.activity_id = activity_id
        model.logon_id = logon_id
        model.out_biz_no = out_biz_no
        request = AlipayUserDtbankcustActivityorderQueryRequest(biz_model=model)
        response_content = self.voucherclient.execute(request)
        return response_content


def rsa_long_encrypt(message):
    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/wx_apiclient_key.pem"), 'r') as f:
        apiclient_key = f.read()
    rsakey = RSA.importKey(apiclient_key)
    cipher = sign_PKCS1_v1_5.new(rsakey)
    rand_hash = SHA256.new()
    rand_hash.update(message.encode())
    signature = cipher.sign(rand_hash)
    return str((base64.b64encode(signature)), encoding="utf-8")


def rsa_long_encrypt_sichun(apiclient_key, message):
    # with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "certificate/wx_apiclient_key_sichun.pem"), 'r') as f:
    #     apiclient_key = f.read()
    rsakey = RSA.importKey(apiclient_key)
    cipher = sign_PKCS1_v1_5.new(rsakey)
    rand_hash = SHA256.new()
    rand_hash.update(message.encode())
    signature = cipher.sign(rand_hash)
    return str((base64.b64encode(signature)), encoding="utf-8")


def pay_transactions_jsapi(data_json, appid):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi'
    nonce_str = random_str()
    timestamp = int(time.time())
    json_str = json.dumps(data_json)
    message = f'POST\n/v3/pay/transactions/jsapi\n{timestamp}\n{nonce_str}\n{json.dumps(data_json)}\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('post', UFDODER_URL, data=json_str, headers=headers)
    data_dict = json.loads(response.content)  # 将请求返回的数据转为字典
    if 'code' in data_dict:
        return data_dict
    message = f'{appid}\n{timestamp}\n{nonce_str}\nprepay_id={data_dict["prepay_id"]}\n'
    signature = rsa_long_encrypt(message)
    data = {
        'appId': appid,
        'timeStamp': f'{timestamp}',
        'nonceStr': nonce_str,
        'package': f'prepay_id={data_dict["prepay_id"]}',
        'signType': 'RSA',
        'paySign': signature
    }
    return data


def cmf_pay_transactions_jsapi(data_json):
    url = 'https://api.gdwxyf.com/api/miniAppPay.do'
    key = '6715C7D4435343BA0459EAEC2334D81B'
    sign = get_sign(data_json, key)
    data_json['sign'] = sign
    response = requests.post(url=url, json=data_json)
    result = response.json()
    if result['result_code'] == 'success':
        data = {
            'appId': result['appid'],
            'timeStamp': result['time_end'],
            'nonceStr': result['nonce_str'],
            'package': result['pre_pay_id'],
            'signType': 'RSA',
            'paySign': result['pay_sign'],
            'out_trade_no': result['out_trade_no']
        }
        return data
    else:
        return result


def cmf_pay_query_order(order_id):
    url = 'https://api.gdwxyf.com/api/GetNotifyOrderMsg.do'
    key = '5ABAA82CD9664478BDA7181339B12B1C'
    data = {
        "program_id": "201519556510031029",
        "order_id": order_id
    }
    sign = get_sign(data, key=key)
    data['sign'] = sign
    response = requests.post(url=url, json=data)
    return response.json()


def pay_transactions_native(data_json):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/v3/pay/transactions/native'
    nonce_str = random_str()
    timestamp = int(time.time())
    json_str = json.dumps(data_json)
    message = f'POST\n/v3/pay/transactions/native\n{timestamp}\n{nonce_str}\n{json.dumps(data_json)}\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('post', UFDODER_URL, data=json_str, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def pay_transactions_refund(data_json):
    UFDODER_URL = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds'
    nonce_str = random_str()
    timestamp = int(time.time())
    json_str = json.dumps(data_json)
    message = f'POST\n/v3/refund/domestic/refunds\n{timestamp}\n{nonce_str}\n{json.dumps(data_json)}\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('post', UFDODER_URL, data=json_str, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def query_transactions_refund(out_refund_no):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds/{out_refund_no}'
    nonce_str = random_str()
    timestamp = int(time.time())
    message = f'GET\n/v3/refund/domestic/refunds/{out_refund_no}\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('get', UFDODER_URL, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def query_transactions_pay(out_trade_no):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}?mchid=1486198522'
    nonce_str = random_str()
    timestamp = int(time.time())
    message = f'GET\n/v3/pay/transactions/out-trade-no/{out_trade_no}?mchid=1486198522\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('get', UFDODER_URL, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def favor_distributed_coupons(data_json, openid):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/users/{openid}/coupons'
    nonce_str = random_str()
    timestamp = int(time.time())
    json_str = json.dumps(data_json)
    message = f'POST\n/v3/marketing/favor/users/{openid}/coupons\n{timestamp}\n{nonce_str}\n{json.dumps(data_json)}\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('post', UFDODER_URL, data=json_str, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def favor_query_coupons(coupon_id, openid, appid):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/users/{openid}/coupons/{coupon_id}?appid={appid}'
    nonce_str = random_str()
    timestamp = int(time.time())
    message =f'GET\n/v3/marketing/favor/users/{openid}/coupons/{coupon_id}?appid={appid}\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt(message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="1486198522",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="7469493EF80EFED22ED16D257F177118B2B12105"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.get(UFDODER_URL, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def favor_distributed_coupons_sichun(data_json, openid, channel):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/users/{openid}/coupons'
    nonce_str = random_str()
    timestamp = int(time.time())
    json_str = json.dumps(data_json)
    message = f'POST\n/v3/marketing/favor/users/{openid}/coupons\n{timestamp}\n{nonce_str}\n{json.dumps(data_json)}\n'
    signature = rsa_long_encrypt_sichun(channel.pub_key, message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="{channel.mchid}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{channel.serial_no}"',
               'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.request('post', UFDODER_URL, data=json_str, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def favor_query_coupons_sichun(coupon_id, openid, appid, channel):
    UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/users/{openid}/coupons/{coupon_id}?appid={appid}'
    nonce_str = random_str()
    timestamp = int(time.time())
    message =f'GET\n/v3/marketing/favor/users/{openid}/coupons/{coupon_id}?appid={appid}\n{timestamp}\n{nonce_str}\n\n'
    signature = rsa_long_encrypt_sichun(channel.pub_key, message)
    headers = {'Content-Type': 'application/json',
               'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="{channel.mchid}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{channel.serial_no}"',
               'Wechatpay-Serial': '', 'Accept': 'application/json',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    response = requests.get(UFDODER_URL, headers=headers)
    data_dict = json.loads(response.content)
    return data_dict


def md5_rsa_sign(data_dict):
    privkey = '''-----BEGIN RSA PRIVATE KEY-----
    MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCv2NxKnFEfYNSsXgrokf1bMfbtRIMuA0x1/fUTinZiQHxGCg4HYP1xPMWXq1KQ9ZUO1gpioEKE1fZDCt58lJuPb+Qv0PKVf40tfAtKQ4Dcq754bf9AWaxWf8/OSPtK7HlsxOwM0V+i7VCkNnR092a4MtFj/NxrhSk4ylAvcnIzREcN33Y/rGCBQLAz1sY306WiXn5/mrCGh5c1sJcvS5hC9N2Oit8Fx6oTec6O+mShzwQnHd4ktum5gHEyq5vuAHlGNckuwA66R/HQS4CERG4dXl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2kl2+6n0FVaANor/3q17pi70/GM0c77woqvyyA/RvBGsAy09BAoGAZ/FBP2q7rqEYb1Jq9OPgemYhTIWsfD07kT4crnMbwdquBX39aYpxKzJlOCVUfDOK6psPRpe1uj2HtXpOPPTn1QPRIB+7R4mdW2nhVcJ+pvooeC5PXDZjkfysM8dja69u//q4KDx8ltcFgWw50M031GQaLax/ZT0oO8PJ/Ep4XJ4=
    -----END RSA PRIVATE KEY-----'''
    message = json.dumps(dict(sorted(data_dict.items()))).replace(' ', '')
    rsakey = RSA.importKey(privkey)
    cipher = sign_PKCS1_v1_5.new(rsakey)
    rand_hash = MD5.new()
    rand_hash.update(message.encode())
    signature = cipher.sign(rand_hash)
    return str((base64.b64encode(signature)), encoding="utf-8")


def favor_meituan_query_coupons(serialNo):
    url = 'https://promo.meituan.com/merchant/coupons/assign/query'
    body = {
        "merchantId": 436,
        "serialNo": serialNo,
    }
    sign = md5_rsa_sign(body)
    body['sign'] = sign
    response = requests.post(url=url, json=body)
    return response.json()


def favor_meituan_coupons(serialNo, batchId, phone):
    ''''''
    url = 'https://promo.meituan.com/merchant/coupons/assign'
    body = {
        "serialNo": int(serialNo),
        "batchInfoDtos": [{"batchId": int(batchId), "count": 1}],
        "merchantId": 436,
        "phone": phone,
    }
    sign = md5_rsa_sign(body)
    body['sign'] = sign
    response = requests.post(url=url, json=body)
    result = response.json()
    if result['status'] != 'success':
        if result['errorCode'] in [100001, 100005]:
            result = favor_meituan_query_coupons(serialNo)
    return result


from users.models import CustomerUser
from equity_mall.utils.qiniu_storage import pic_upload, pic_delete
def wash_customer_user_iden():
    queryset = CustomerUser.objects.filter(identification_front_copy__contains='identification_front_copy')
    for query in queryset:
        identification_front_copy = query.identification_front_copy.url
        img_str = requests.get(url=identification_front_copy).content
        pic_delete(query.identification_front_copy.name)
        try:
            img_id = f'youhuiquanyi/customer/identification_copy/{random_str(32)}.png'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            print('图片上传失败,请重新上传!')
            continue
        query.identification_front_copy = img_id
        query.save()
        print(query.id)
    print(len(queryset))


if __name__ == '__main__':
    # wash_customer_user_iden()
    pass
    # from orders.models import OrderInfo
    # query_set = OrderInfo.objects.filter(id__in=[3472378,3472428,3472436,3472467,3472468,3472668,3472696,3472710,3472741,3472744,3472758,3472784,3472790,3472804,3472824,3472837,3472844,3472867,3472906,3472910,3472948,3472976,3472981,3472989,3473034,3473046,3473055,3473057,3473064,3473069,3473118,3473131,3473176,3473196,3473226,3473278,3473331,3473376,3473380,3473580,3473829,3474167,3474310,3474337,3474370,3474452,3474511,3475028,3475519,3475523,3475710,3475950,3475989,3476088,3476198,3476666,3476685,3477055,3477253,3477300,3477339,3477415,3477510,3477749,3477868,3478004,3478036,3478459,3479412,3479584,3479600,3479981,3480290,3480474,3480677,3480870,3481390,3481458,3481480,3481621,3481850,3482472,3483049,3483164,3483597,3483638,3484489,3484832,3486231,3486271])
    # for query in query_set:
    #     try:
    #         result = query_transactions_refund(query.out_refund_no)
    #         print(query.id, result['amount']['refund'])
    #     except:
    #         print(query.id, result)
    # result = query_transactions_refund('20231007204948770153637705')
    # result = favor_query_coupons('73199199730', 'o4Gir6gYb1KVnRIwaIWluz94cSTE', 'wx159b5cd8dbd2bb8c')
    # print(result)
    # data_json = {}
    # data_json['appid'] = 'wx950122ad80dc97c9'
    # data_json['mchid'] = '1486198522'
    # data_json['description'] = '矿泉水1一瓶'
    # data_json['out_trade_no'] = '2023120513032219439'
    # data_json['notify_url'] = 'https://api.sutpay.com/cpay/wxpay_result/'
    # data_json['amount'] = {"total": 100}
    # data_json['goods_tag'] = 'xinxiang'
    # print(pay_transactions_native(data_json))
    # print(favor_meituan_coupons('4362024082715113042', 59478, "13711148076"))
    alipay_obj = AlipayOpen()
    # result = json.loads(alipay_obj.transunitransfer_query_jiangxi88_jizhangben('20250306142705949931016332'))
    # for i in ["202411110007300257590S2B890L"]:
    #     result = json.loads(alipay_obj.voucherquery(i))
    #     print(result)
    result = json.loads(alipay_obj.voucherquery('202504230007300286310VV5W62B'))
    print(result)
    # result = json.loads(alipay_obj.campaign_drawcamp_trigger_login_id('13510535265', 'CP192525997', '20241224074453001'))
    # print(result)

    # import datetime
    # from random import randint
    # from activities.models import Channel
    # channel = Channel.objects.get(id=4)
    # data_json = {
    #     "stock_id": '19599575',
    #     "out_request_no": f"{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}{'%06d' % randint(0, 999999)}",
    #     "appid": 'wx950122ad80dc97c9',
    #     "stock_creator_mchid": '1666840291'
    # }
    # result = favor_distributed_coupons_sichun(data_json, 'omjwf4_HKyrd7ubQPKbTcEyrDJdw', channel)
    # print(result)
    # result = favor_query_coupons_sichun('98827788473', 'oI_D75eRRWKNUK2VLFGnVrwqkMl4', 'wx5f0a0165d342d788', channel)
    # print(result)